package com.gateway.gateway.bus;

import com.alibaba.nacos.common.utils.JacksonUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Component
public class LogFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("=====" + exchange.getRequest().getPath().value() + "=====");

//        HttpHeaders headers = exchange.getRequest().getHeaders();
//        Set<Map.Entry<String, List<String>>> entries = headers.entrySet();
//        for (Map.Entry<String, List<String>> m : entries) {
//            System.out.println("=====" + m + "=====");
//        }
//        return chain.filter(exchange);


//        // 1.获取请求参数
//        ServerHttpRequest request = exchange.getRequest();
//        MultiValueMap<String, String> params = request.getQueryParams();
//        // 2.获取authorization参数
//        String auth = params.getFirst("authorization");
//        // 3.校验
//        if ("admin".equals(auth)) {
//            // 放行
//            return chain.filter(exchange);
//        }
//        // 4.拦截
//        // 4.1.认证失败状态
//        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//        // 4.2.结束处理
//        return exchange.getResponse().setComplete();



        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        // 2.获取authorization参数
        String auth = params.getFirst("authorization");
        // 3.校验
        if ("admin".equals(auth)) {
            // 放行
            return chain.filter(exchange);
        }
        //3.2封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "未登录");
        map.put("code", "NOTLOGING");

        //3.3作JSON转换
        String json = JacksonUtils.toJson(map);
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        exchange.getResponse().beforeCommit(() -> {
            exchange.getResponse().getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return Mono.empty();
        });
        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return exchange.getResponse().writeWith(Mono.just(buffer));
    }
}
